<template>
  <section class="pay_content">
    <el-page-header @back="goBack" content="收费"></el-page-header>
    <div class="main_left">
      <div class="pay_left">
        <div class="pay_left_item">
          订单号：
          <br />
          {{detail.orderCode}}
        </div>
        <div class="pay_left_item pay_left_mb">
          应收金额：
          <br />
          <span class="pay_total">￥{{detail.actualAmount}}</span>
        </div>
        <div class="pay_left_item">
          患者姓名：
          <br />
          {{detail.patientName}}
        </div>
        <div class="pay_left_item">
          就诊日期：
          <br />
          {{detail.cureTime}}
        </div>
        <span style="cursor: pointer;" @click="getDetail()">查看收费明细 ></span>
      </div>
    </div>
    <div class="main_right">
      <div class="main_right_c">
        <el-form ref="form" :model="form" :rules="rules" label-width="140px">
          <el-form-item label="折扣" prop="discountNumber" style="width:300px;">
            <el-checkbox v-model="form.isDiscount" @change="computeMoney" name="type"></el-checkbox>
            <el-input
              style="width:200px;"
              type="number"
              v-if="form.isDiscount"
              @blur="computeMoney"
              v-model="form.discountNumber"
            >
              <template slot="append">折</template>
            </el-input>
          </el-form-item>
          <el-form-item label="是否减免：" prop="reductionType" :rules="derate? reductionRule :[]" >
            <el-checkbox
              v-model="derate"
              @change="computeMoney"
              style="width:120px;"
            >是</el-checkbox>
            <div v-if="derate==true" style="display:inline-block;width:100%;">
              <el-checkbox-group @change="changePayWay(1)" v-model="form.reductionType">
                <el-checkbox
                  v-for="(value,key) in paytypeList"
                  :key="key" :label="key" :value="key"
                  style="width:150px"
                >{{value}}</el-checkbox>
              </el-checkbox-group>
            </div>
          </el-form-item>
          <el-form-item  v-for="(item,index) in form.reductionWayArr"
            :label="item.name+'：'"
            :key="item.key" :prop="'reductionWayArr.' + index + '.payMoney'" :rules="residueRule">
             <el-input style="width:300px" @blur="computeMoney" v-model="item.payMoney">
                 <el-button slot="append" >元</el-button>
             </el-input>
          </el-form-item>
          <el-form-item label>
            <div class="needPay">还需支付：￥{{residueMoney}}</div>
          </el-form-item>
          <el-form-item label="支付方式："  prop="paylist" >
               <el-checkbox-group @change="changePayWay(2)" v-model="form.paylist">
                    <el-checkbox :style="key==0?'width:160px':'width:110px'" v-for="(value,key) in payWayList" :key="key" :label="key" :value="key">
                        {{value}}
                        {{key==0? '(￥'+ balanceMoney+')':''}}
                    </el-checkbox>
               </el-checkbox-group>
          </el-form-item>
          <el-form-item  v-for="(item,index) in form.payWayArr"
            :label="item.name+'：'"
            :key="item.key"  :prop="'payWayArr.' + index + '.payMoney'" :rules="payMoneyRule" >
             <el-input style="width:300px" @blur="computeMoney" v-model="item.payMoney">
                 <el-button slot="append" >元</el-button>
             </el-input>
          </el-form-item>
          <el-form-item
            label="备注："
            prop="remark"
            :rules="form.isDiscount || derate ? remarkRule : []"
          >
            <el-input type="textarea" v-model.trim="form.remark" style="width:300px;"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-if="qxBtns.pay" :loading="btnLoading" @click="onSubmit()">收费</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </section>
</template>
<script>
import validate from "@/_js/validate.js";
import enumArr from "../_enum/enum";
export default {
  data() {
    return {
        paytypeList:[], 
        form:{
            isDiscount:false,
            //备注
            remark:'',
            //折扣数
            discountNumber:'',
            //减免类型
            reductionType:[],
            //支付方式
            paylist:['3'],

            payWayArr:[{
              key: "3",
              name: "POS机支付",
              payMoney: ""
            }],
            reductionWayArr:[]
        },
        //是否减免
        derate:false,
        //实时计算支付金额
        residueMoney:'',
        detail:{
            //患者姓名
            patientName:'',
            //订单编号
            orderCode:'',
            //实际支付金额
            actualAmount:'',
            //原总金额
            totalAmount:'',
            //就诊日期
            cureTime:'',
            patientId:''
        },
        rules:{
            discountNumber:[{ validator: validate.FloatByTwo, trigger: "blur" }],
            paylist:[{ required: true, message: '请选择支付方式', trigger: 'change' }],
        },
        //支付方式
        payWayList:enumArr.payArr,
        //按钮加载
        btnLoading:false,
        //账户余额
        balanceMoney:0,
        disRsidueMoney:0,
        payMoneyRule:[
            { required: true, message: '请输入支付金额', trigger: 'blur'},
            { validator: validate.integerAndFloat, trigger: 'blur' }
        ],
        residueRule:[
           { required: true, message: '请输入减免金额', trigger: 'blur'},
            { validator: validate.integerAndFloat, trigger: 'blur' }
        ],
        remarkRule:[{ required: true, message: '请输入描述', trigger: 'blur' }],
        reductionRule:[{ required: true, message: '请选择减免方式', trigger: 'change' }],
        qxBtns:{}
    };
  },
  created() {
    this.getQX();
    this.getBasicDate();
  },
  mounted() {
    this.open();
  },
  methods: {
    getBasicDate() {
      this.getCommonConfigByKey("收费减免类型").then((res) => {
          let list=res;
          let arr={};
          list.forEach(it=>{
              arr[it.id]=it.desc;
          })
        this.paytypeList = arr;
      });
    },
   async open() {
       await this.$api.getOrderDetailByMedical({orderId:this.$route.query.id}).then(res=>{
            if(res.executed){
                const {cureTime,actualAmount,patientName,orderCode,totalAmount,patientId} =res.dataBody;
                this.detail={cureTime,actualAmount,patientName,orderCode,totalAmount,patientId};
                this.form.payWayArr[0].payMoney=actualAmount;
                this.residueMoney=Number(0).toFixed(2);
            }
        })
         await this.$api.getPatientInfo({patientId: this.detail.patientId,hpId: this.adminUser.hpId}).then((res) => {
                if (res.executed) {
                    this.balanceMoney = res.dataBody.account.amount;
                }
        });
    },
    changePayWay(type){
        let list=[];
        if(type==1){
            let paylist=this.form.reductionType;
            for(let i =0;i<paylist.length;i++){
                list.push({name:this.paytypeList[paylist[i]],payMoney:'',key:paylist[i]});
            }
            this.form.reductionWayArr=list;
        }else{
            let paylist=this.form.paylist;
            for(let i =0;i<paylist.length;i++){
                list.push({name:this.payWayList[paylist[i]],payMoney:'',key:paylist[i]});
            }
            if(list.length==1){
              list[0].payMoney=this.residueMoney;
            }
            this.form.payWayArr=list;
        }
       this.computeMoney();
    },
    getDetail() {
      let j = {
          id: this.$route.query.id,
          patientId: this.detail.patientId
        };
      this.$router.push({
        path: "/page/hasChargeDetail",
        query: this.getUrlToken(j)
      });
    },
    goBack() {
      this.$router.push({
        path: "/page/chargeIndexV2",
        query: this.getUrlToken({
          // total: th.totalMoney,
          type: 1,
        }),
      });
    },
    //计算消费金额
    computeMoney() {
      let total = this.detail.actualAmount; //订单总金额;
      let tMoney = this.detail.actualAmount;
      let patientMoney = this.balanceMoney; //用户账户余额
      if(this.form.payWayArr.length==1){
          this.form.payWayArr[0].payMoney=total;
      } 
      let discountnum =
        this.form.discountNumber == "" ||
        this.form.discountNumber > 10 ||
        this.form.discountNumber < 0
          ? 10
          : this.form.discountNumber; //折扣数
      discountnum = Number(discountnum / 10);
      let reductionlist = this.form.reductionWayArr;
      let sourcelist = this.form.payWayArr; //支付方式列表
      let residueMoney = this.residueMoney; //剩余待支付金额
      /**方式一、折扣率 */
      if (this.form.isDiscount) {
        if (Number(total) < 0) {
          this.$message.warning("折扣数有误");
          this.form.discountNumber = "";
          discountnum = 10;
          this.disRsidueMoney=0
        } else {
          let disMoney=Number(tMoney * (1 - discountnum)).toFixed(2);
          total =(parseInt(Number(total - disMoney) * 100 ) / 100 ).toFixed(2)  ; //计算折扣金额
          this.disRsidueMoney=Number(tMoney - total).toFixed(2) ;
        }
      }else{
          this.form.discountNumber = "";
          this.disRsidueMoney=0
      }
      /**方式二、减免金额 */
      //当减免金额大于剩余支付金额的情况，将提示用户重新输入金额;
      if(reductionlist.length>0){
          reductionlist.map((it) => {
          it.payMoney =
            Number(it.payMoney) < 0
              ? Number(patientMoney).toFixed(2)
              : Number(it.payMoney).toFixed(2);
          if (
            Number(it.payMoney) <= patientMoney &&
            Number(total).toFixed(2) >= Number(it.payMoney)
          ) {
            total -= Number(it.payMoney);
          } else if (Number(total).toFixed(2) >= Number(it.payMoney)) {
            total -= Number(it.payMoney);
          } else {
            it.payMoney = 0;
            this.computeMoney();
          }
        });
      }
      /**方式三、不同支付 */
      //获取不同支付方式支付金额
      if (sourcelist.length>0) {
        sourcelist.forEach((it) => {
          it.payMoney = Number(it.payMoney) < 0? Number(patientMoney).toFixed(2): Number(it.payMoney).toFixed(2);
          if(it.key==0){
            if (Number(it.payMoney) <= patientMoney && Number(total).toFixed(2) >= Number(it.payMoney)) {
                total -= Number(it.payMoney);
            }else {
                it.payMoney = sourcelist.length==1?Number(total).toFixed(2):0;
                total -= Number(it.payMoney);
                // console.log("11")
                // this.computeMoney();
            }
          }else{
            if (Number(it.payMoney) <= patientMoney && Number(total).toFixed(2) >= Number(it.payMoney)) {
                total -= Number(it.payMoney);
            } else if (Number(total).toFixed(2) >= Number(it.payMoney)) {
                total -= Number(it.payMoney);
            } else {
                it.payMoney =  sourcelist.length==1? Number(total).toFixed(2):0;
                total -= Number(it.payMoney);
                // this.computeMoney();
            }
          }
        });
      }
      this.residueMoney =
        Number(total).toFixed(2) == 0
          ? Number(0).toFixed(2)
          : Number(total).toFixed(2);  
      // if(this.form.payWayArr.length==1){
      //     this.form.payWayArr[0].payMoney=total;
      // }     
    },
    //提交收费订单
    onSubmit() {
        const {remark, payWayArr , reductionWayArr,discountNumber }=this.form;
        this.btnLoading=true;
        this.$refs["form"].validate(valid=>{
            if(valid){
                 let item=[];
                 if(this.form.isDiscount){
                     item.push({source:5,payAmount:this.disRsidueMoney,extra:Number(discountNumber/10).toFixed(2)})
                 }
                 payWayArr.forEach(it=>{
                   item.push({source:it.key,payAmount:it.payMoney})
                 });
                 reductionWayArr.forEach(it=>{
                     item.push({source:it.key,payAmount:it.payMoney})
                 })
                this.$api.payOrder({orderId:this.$route.query.id,remark:this.form.remark,payWays:JSON.stringify(item)}).then(res=>{
                    if(res.executed){
                        this.$message.success("结算成功");
                        this.btnLoading=false;
                        this.$router.push({path: '/page/chargeIndexV2',query: this.getUrlToken({type: 2})});
                    }else{
                        this.$message.error(res.message);
                        this.btnLoading=false;
                    }
                })
            }
        })
    },
  }
};
</script>
<style lang="scss" scoped>
@import "./_css/pay.scss";
.pay_content {
  &::after {
    display: block;
    clear: both;
    visibility: hidden;
    height: 0;
    overflow: hidden;
    content: ".";
  }
  .el-radio {
    width: 120px;
    margin: 0;
    padding: 0;
  }
  .el-form-item {
    margin-bottom: 15px;
  }
  .el-page-header {
    margin-bottom: 20px;
  }
}
.main_left {
  width: 250px;
  float: left;
  position: relative;
  margin-right: -250px;
}
.main_right {
  width: 100%;
  float: right;
  .main_right_c {
    margin-left: 270px;
  }
}
.pay_left {
  padding: 20px;
  background: #40a48b;
  color: #fff;
  .pay_left_item {
    margin-bottom: 30px;
    line-height: 1.5;
  }
  .pay_left_item.pay_left_mb {
    margin-bottom: 80px;
  }
  .pay_total {
    font-size: 30px;
    color: #f9ed54;
  }
}
.el-checkbox-group .el-checkbox {
  width: 120px;
  float: left;
  margin: 0;
  padding: 0;
}
.needPay {
  font-size: 18px;
  font-weight: bold;
  color: #ff5b5b;
}
.danger {
  color: #ff5b5b;
}
.el-form-item__content .el-input-group {
  margin-bottom: 15px;
}
.ml20 {
  margin-left: 20px;
}
</style>